#include "censorwords.h"
#include "acsmx.h"
using namespace std;




int32_t CensorChecker::initCensorWords(const char *config){

	if(!config){
		//DEBUG_LOG_S("config is null");
		cout<<"config is null"<<endl;
		return -1;
	}

	FILE *fp = fopen(config, "r");
	if(fp == NULL) {
		//DEBUG_LOG_S("open file error!");
		cout<<"open file error!"<<endl;
		return -1;
	}

	_ACM = acsmNew();
	if(_ACM == NULL) {
		//DEBUG_LOG_S("acm is null!");
		cout<<"acm is null"<<endl;
		return -1;
	}

	char buf[512] = {'\0'};
	while(fgets(buf, 512, fp)!=NULL) {
		char *p = strchr(buf, '\n');
		if(p!=NULL) {
			*p = '\0';
		}
		if(strlen(buf)!=0) {
			acsmAddPattern(_ACM, (unsigned char*)buf, strlen(buf), 0);
		}
	}
	acsmCompile(_ACM);
	
	//DEBUG_LOG_S("init censorwords ok");
	cout<<"init censorwords ok"<<endl;

	return 0;

}



int32_t CensorChecker::censorReplace(
		const std::string &input,
		std::string &output){
	
	
	char *replace = NULL;
	char *tmpbuff = NULL;

	if((int32_t)input.size() < MAXBUFFERSIZE){
		memset(_rbuff,0,MAXBUFFERSIZE);
		replace = _rbuff;
	}
	else{
		tmpbuff = new char[input.size()+1];	
		replace = tmpbuff;
	}

	memcpy(replace,input.c_str(),input.size());
	replace[input.size()] = '\0';

	acsmReplace(_ACM, (unsigned char *)replace, input.size());

	output = replace;

	if(tmpbuff){
		delete tmpbuff;
		tmpbuff = NULL;
	}

	return 0;

}


/*
 * 返回：=0 不存在敏感词
 *		 >0 存在敏感词
 *		 <0 失败
 */
//int32_t CensorChecker::censorCheck(const std::string &input) {
int32_t CensorChecker::censorCheck(
		const char *input,
		const int32_t len) {

	if (!input || !len) {
		cerr<<"input is empty"<<endl;
		return -1;
	}

	string new_str; 
	if (censorReplace(input,new_str) < 0) {
		cerr<<"censorReplace error"<<endl;
		return -1;
	}

	if (new_str != input) {
		cerr<<"exist censor words"<<endl;
		return 1;
	}

	return 0;
}


int32_t CensorChecker::releaseCensorWords(){
	cerr<<"releaseCensorWords---------------------------------"<<endl;	
	if(_ACM){
		acsmFree(_ACM);
	}

	return 0;
}
